from urllib import request,parse
import json
import time
import random
import hashlib

base_url = 'http://fanyi.youdao.com/translate_o?smartresult=dict&smartresult=rule'

def md5(value):
    md5 = hashlib.md5()
    md5.update(bytes(value,encoding='utf-8'))
    res = md5.hexdigest()
    return res


def fanyi(kw):
    salt = int(time.time() * 1000) + random.randint(1,10)
    sign = "fanyideskweb" + kw + str(salt) + "ebSeFb%=XZ%T[KZ)c(sy!"
    sign = md5(sign)
    # print(salt)
    # print(sign)
    # return

    form = {
        "i": kw,
        "from": "AUTO",
        "to": "AUTO",
        "smartresult": "dict",
        "client": "fanyideskweb",
        "salt": salt,
        "sign": sign,
        "doctype": "json",
        "version": "2.1",
        "keyfrom": "fanyi.web",
        "action": "FY_BY_REALTIME",
        "typoResult": "false"
    }

    # 发送主体
    form = parse.urlencode(form)

    headers = {
        "Host": "fanyi.youdao.com",
        "Connection": "keep-alive",
        "Content-Length": len(form),
        "Accept": "application/json, text/javascript, */*; q=0.01",
        "Origin": "http://fanyi.youdao.com",
        "X-Requested-With": "XMLHttpRequest",
        "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/66.0.3359.181 Safari/537.36",
        "Content-Type": "application/x-www-form-urlencoded; charset=UTF-8",
        "Referer": "http://fanyi.youdao.com/",
        "Accept-Language": "zh-CN,zh;q=0.9",
        "Cookie": "OUTFOX_SEARCH_USER_ID=1013580002@10.169.0.84; OUTFOX_SEARCH_USER_ID_NCOO=216555653.08909458; UM_distinctid=160c4f0adef526-00416b6000ee1a-b7a103e-fa000-160c4f0adf0501; JSESSIONID=aaabXfPpDRm72bppOMYpw; fanyi-ad-id=44881; fanyi-ad-closed=1; ___rl__test__cookies=1528784004293",
    }

    req = request.Request(base_url,data=bytes(form,encoding='utf-8'),headers=headers)
    response = request.urlopen(req)

    # 获取翻译结果
    data = response.read().decode('utf-8')
    data = json.loads(data)
    # print(data)
    if 'smartResult' in data:
        for res in data['smartResult']['entries']:
            if res:
                print(res)
    if  'translateResult' in data:
        for item in data['translateResult']:
            print(item[0]['tgt'])

if __name__ == '__main__':
    while True:
        kw = input('输入翻译:')
        fanyi(kw)
